/**
 * 缓动动画
 * 例：buffer('box', {'top':500,'left':600})
 * @param {object}obj
 * @param {JSON}json
 * @param {function}fn
 */
function buffer(obj, json, fn) {
    //1清除定时器
    clearInterval(obj.timer);

    //设置初始值
    var begin = 0, target = 0, speed = 0;
    //设置定时器
    obj.timer = setInterval(function () {
        //设置旗帜
        var flag = true;
        for (key in json) {
            //获取初始值
            if (key === 'opacity') {
                begin = parseInt(parseFloat(getCSSAttrVal(obj, key)) * 100);
                target = parseInt(json[key] * 100);
            } else if (key === 'scrollTop') { // 滚动到头部
                begin = scroll().top;
                target = parseInt(json[key]);
            } else {
                begin = parseInt(getCSSAttrVal(obj, key)) || 0;
                target = parseInt(json[key]);
            }

            //计算步长
            if (key === 'z-index') {
                speed = target;
            }
            else {
                //步长
                speed = (target - begin) * 0.2;
                //判断是否向上取整数
                speed = speed >= 0 ? Math.ceil(speed) : Math.floor(speed);
            }

            //动起来
            if (key === 'z-index') {
                obj.style.zIndex = speed;
            }
            else if (key === 'opacity') {
                obj.style.opacity = (begin + speed) / 100;
                obj.style.filter = `alpha(opacity=${begin + speed})`;
            }
            else if (key === 'scrollTop') {
                obj.documentElement.scrollTop = begin + speed;
            }
            else {
                obj.style[key] = begin + speed + 'px';
            }

            //判断
            if (begin !== target) {
                flag = false;
            }
        }
        //清除定时器
        if (flag) {
            clearInterval(obj.timer);
            //判断回调函数
            if (fn) {
                fn();
            }
        }
    }, 20)
}

function getCSSAttrVal(obj, arrt) {
    return obj.currentStyle ? obj.currentStyle[arrt] : window.getComputedStyle(obj, null)[arrt];
}


/**
 * 获取滚动的头部距离和左边距离
 * scroll().top;scroll().left
 * @returns {{top: number, left: number}}
 */
function scroll() {
    if (window.pageYOffset !== null) {
        return {
            top: window.pageYOffset,
            left: window.pageXOffset
        }
    } else if (document.compatMode === 'CSS1Compat') {
        return {
            top: document.documentElement.scrollTop,
            left: document.documentElement.scrollLeft
        }
    } else {
        return {
            top: document.body.scrollTop,
            left: document.body.scrollLeft
        }
    }
}